package com.qidian.mes.qc.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mes.pojo.QcIndex;
import com.qidian.mes.qc.mapper.IndexMapper;
import com.qidian.mes.qc.service.IndexService;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author 朱静炜
 * @Company 起点编程
 * @Time 2023/10/27 9:59
 * @Description
 */
@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private IndexMapper indexMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public MESResult deleteById(Long indexId) {
        if (getById(indexId).getData() == null){
            return MESResult.empty("数据不存在");
        }
        return MESResult.ok(indexMapper.deleteById(indexId));
    }

    @Override
    public MESResult getById(Long indexId) {
        return MESResult.ok(indexMapper.getById(indexId));
    }

    @Override
    public MESResult update(QcIndex qcIndex) {
        if (getById(qcIndex.getIndexId()).getData() == null){
            return MESResult.empty("数据不存在");
        }
        return MESResult.ok(indexMapper.update(qcIndex));
    }

    @Override
    public MESResult genId() {
        String key = "indexID";
        StringBuilder id = new StringBuilder();
        // 从redis获取序列
        Long idTemp = stringRedisTemplate.opsForValue().increment(key);
        String idStr = idTemp.toString();
        if (idStr.length() < 5) {
        // 前面加0
            for (int i = 0; i < 5 - idStr.length(); i++) {
                idStr = '0' + idStr;
            }
        }
        id.append(idStr);
        return MESResult.ok(id);
    }

    @Override
    public MESResult save(QcIndex qcIndex) {
        if (qcIndex.getIndexType() == null || qcIndex.getIndexName() == null){
            return MESResult.empty("信息不能为空");
        }
        else {
            return MESResult.ok(indexMapper.save(qcIndex));
        }
    }

    @Override
    public MESResult list(QcIndex qcIndex, int page, int limit) {
        PageHelper.startPage(page, limit);
        List<QcIndex> list = indexMapper.list(qcIndex);
        // 组织一个分页对象。（页码，每页大小，最大页码，数据，总条数）
        PageInfo<QcIndex> pageInfo = new PageInfo<>(list);
        return MESResult.ok(pageInfo);
    }
}
